package ${DefaultRepositoryPackage};

import com.askj.integration.event.storage.LocalDomainEventResolver;
import com.askj.integration.infrastructure.aggregate.AggregateEventAwareSupport;
import com.askj.integration.infrastructure.proxy.IMapperProxy;
import ${EntityPackage}.${EntityClassName};
import ${RepositoryPackage}.${entity}Repository;
import ${ProxyPackage}.${entity}Proxy;
import lombok.AccessLevel;
import lombok.Setter;
import lombok.NonNull;
import org.springframework.context.ApplicationEvent;
import org.springframework.stereotype.Repository;
import com.askj.integration.domain.exception.EntityException;
import java.util.List;
import java.util.Optional;
import java.io.Serializable;
/**
 * @author ${author}
 */
@Repository
<#if entity_aggregate>
public class ${DefaultRepositoryClassName} extends AggregateEventAwareSupport<${EntityClassName}> implements ${entity}Repository {

    @Setter(AccessLevel.PRIVATE)
    private ${entity}Proxy proxy;

    protected ${DefaultRepositoryClassName}(${entity}Proxy proxy) {
        super(${EntityClassName}.class);
        setProxy(proxy);
    }


    @Override
    protected IMapperProxy<${EntityClassName}> proxy() {
        return proxy;
    }

    @Override
    protected boolean saveEvents(List<ApplicationEvent> events) {
        LocalDomainEventResolver.instance().add(events);
        return true;
    }
<#list table.fields as field><#if field.propertyName=='openId' && generate_query_by_openid>
    public  Optional<${EntityClassName}> forOpenId(String openId){
        return proxy.forOpenId(openId);
    }
</#if></#list>
<#else>
public class Default${entity}Repository implements ${entity}Repository {

    @Setter(AccessLevel.PRIVATE)
    private ${entity}Proxy proxy;

    protected ${DefaultRepositoryClassName}(${entity}Proxy proxy) {
        setProxy(proxy);
    }


    @Override
    public ${EntityClassName} save(@NonNull ${EntityClassName} record) throws EntityException {
        if (proxy.save(record)) {
            return record;
        }
        throw new EntityException("保存失败");
    }

    @Override
    public List<${EntityClassName}> remove(@NonNull ${EntityClassName} entity) throws EntityException {
        return proxy.remove(entity);
    }

    @Override
    public Optional<${EntityClassName}> remove(@NonNull Serializable id) throws EntityException {
        return proxy.remove(id);
    }

    @Override
    public Optional<${EntityClassName}> byId(@NonNull Serializable id) {
        return Optional.of(proxy.byId(id));
    }

    @Override
    public long countBy(${EntityClassName} entry) {
        return proxy.countBy(entry);
    }

<#list table.fields as field><#if field.propertyName=='openId' && generate_query_by_openid>
    public  Optional<${EntityClassName}> forOpenId(String openId){
        return proxy.forOpenId(openId);
    }
</#if></#list>

</#if>
}
